<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="文件名称">
              <a-input placeholder="请输入文件名称" v-model="queryParam.fileName"></a-input>
            </a-form-item>
          </a-col>
          <!-- <a-col :md="6" :sm="8">
            <a-form-item label="文件是否训练">
              <a-input placeholder="请输入文件地址" v-model="queryParam.train"></a-input>
            </a-form-item>
          </a-col> -->
          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!--      <a-button type="primary" icon="download" @click="handleExportXls('文件列表')">导出</a-button>-->
      <a-upload
          name="file"
          :multiple="false"
          :action="uploadAction"
          :headers="tokenHeader"
          :showUploadList="false"
          :beforeUpload="beforeUpload"
          @change="handleChange">
        <a-button>
          <a-icon type="upload"/>
          文件上传
        </a-button>
      </a-upload>

      <!-- <a-upload
        name="file"
        :multiple="false"
        :action="minioUploadAction"
        :headers="tokenHeader"
        :showUploadList="false"
        :beforeUpload="beforeUpload"
        @change="handleChange">
        <a-button>
          <a-icon type="upload"/>
          MINIO文件上传
        </a-button>
      </a-upload> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
          style="font-weight: 600">{{
        selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          @change="handleTableChange">


   
        <template slot="progressSlot" slot-scope="text, record,index">
          <div class="" v-if="record.train === 1">
            <dProgress :percentage="100" status="success" :text-inside="true"  :stroke-height="16"/>
          </div>
          <div class=""  v-else>
            <dProgress :percentage="progressQuantity" status="success" :text-inside="true"  :stroke-height="16" v-if="index ===progressStarts"/>
            <dProgress :percentage="0" status="success" :text-inside="true"  :stroke-height="16" v-else/>
          </div>
        </template>

        <template slot="trainSlot" slot-scope="text, record">
          <div class="badge" v-if="record.train === 1" style="background-color: #bbe6e3;color: #3A9B94;">
            已训练
          </div>
          <div class="badge" style="    background-color: #ffdede;color: #FF5E5E;" v-else>
            未训练
          </div>
          <!-- <div class=""  v-else>
            <div class="badge" style="background-color: #bbe6e3;color: #3A9B94;" v-if="index ===progressStarts">
            已训练
          </div>
            <div class="badge" style="    background-color: #ffdede;color: #FF5E5E;" v-else>
            未训练
          </div>
          </div> -->

        </template>

        <span slot="action" slot-scope="text, record,index">
          <!-- <a @click="handlePreview(record)">预览</a>
          <a-divider type="vertical"/>
          <a @click="ossDelete(record.id)">删除</a>
          <a-divider type="vertical"/> -->
          <a @click="trainId(record.id,index)" v-if="record.train !== 1">训练</a>
          <!-- <a v-else style="color: #999;">训练中</a> -->
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->
  </a-card>
</template>

<script>
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import dProgress  from './component/ProGress'
  import { getAction } from '@/api/manage'
  import { DATA_MONITOR,DATA_MONITOR_TEST,DATA_MONITOR_INDEX} from "@/store/mutation-types"
  import { mapActions, mapGetters, mapState } from 'vuex'
  import Vue from 'vue'
  export default {
    name: "OSSFileList",
    mixins: [JeecgListMixin],
    components: {
      dProgress 
    },
    data() {
      return {
        description: '文件列表',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '文件名称',
            align: "center",
            dataIndex: 'fileName'
          },
          {
            title: '训练进度',
            align: "center",
            // dataIndex: 'train',
            scopedSlots: {customRender: "progressSlot"}
          },
          {
            title: '是否训练',
            align: "center",
            dataIndex: 'train',
            // customRender: function (text) {
            //   if (text === 1) {
            //     return '已训练'
            //   } else {
            //     return '未训练'
            //   }
            // },
            scopedSlots: {customRender: "trainSlot"}
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: {customRender: 'action'},
          }
        ],
        url: {
          upload: "/sys/oss/file/upload",
          list: "/sys/oss/file/list",
          delete: "/sys/oss/file/delete",
          minioUpload: "/sys/upload/uploadMinio"
        },
        timer:null, //定时器名称
        dataLock:true,
        progressQuantity:0,
        progressStarts:0,
        clickDisBtn:false,

      }
    },
    computed: {
      uploadAction() {
        return window._CONFIG['domianURL'] + this.url.upload;
      },
      minioUploadAction() {
        return window._CONFIG['domianURL'] + this.url.minioUpload;
      },
    },
    mounted(){
      console.log('dataMonitor',this.dataMonitor())
        console.log('dataMonitorTest',this.dataMonitorTest())
        console.log('dataMonitorIndex',this.dataMonitorIndex())

        let dataMonitor = this.dataMonitor()
        let dataMonitorTest = this.dataMonitorTest()
        let dataMonitorIndex = this.dataMonitorIndex()

      this.$nextTick(function(){
        if(dataMonitor === null){
          this.dataLock = true
        }else{
          // dataMonitorTest[dataMonitorIndex].status = 1
          // console.log('dataMonitor1',dataMonitorTest)
          // this.dataSource = dataMonitorTest

          this.progressStarts = dataMonitorIndex
          // this.setTime()
        }
       
      })


    },
    beforeDestroy(){
     this.clearIntval()
    },
    methods: {
      ...mapGetters(['dataMonitor','dataMonitorTest','dataMonitorIndex']),
      clearIntval(){
        clearInterval(this.timer); // 清除定时器
        this.timer = null;
      },
      setTime(){ 
        this.timer = setInterval(()=>{
          this.progressQuantity ++
          if(this.progressQuantity === 99){
            this.clearIntval()
          }
          console.log('this.progressQuantity = 0',this.progressQuantity)
        },1500)
      },
      beforeUpload(file) {
        console.log('file',file)
        var fileType = file.type;
        var occFile = fileType.split('/')
        console.log('occFile',occFile)
        if (fileType === 'image') {
          if (fileType.indexOf('image') < 0) {
            this.$message.warning('请上传图片');
            return false;
          }
        } else if (fileType === 'file') {
          if (fileType.indexOf('image') >= 0) {
            this.$message.warning('请上传文件');
            return false;
          }
        }else if (occFile[1] !== 'pdf') {
            this.$message.warning('请上传pdf文件');
            return false;
          }
        return true
      },
      handleChange(info) {
        console.log('info',info)
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            this.loadData()
            this.$message.success(`${info.file.name} 上传成功!`);
          } else {
            this.$message.error(`${info.file.response.message}`);
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.response.message}`);
        }
      },
      ossDelete(id) {
        var that = this;
        that.$confirm({
          title: "确认删除",
          content: "是否删除选中文件?",
          onOk: function () {
            that.handleDelete(id)
          }
        });
      },
      trainId(id,index){
        console.log('id',id)
        console.log('index',index)
        if(this.clickDisBtn = true){
          this.$message.info('文件正在训练中')
        }
        var that = this;
        that.$confirm({
          title: "确认训练",
          content: "是否训练选中文件?",
          onOk: function () {
            this.clickDisBtn = true
            that.setHandle(id,index)
            that.handleTrain(id,index)
          }
        });
      },
      setHandle(id,index){
        var setData = JSON.parse(JSON.stringify(this.dataSource));
        var setData1 = JSON.parse(JSON.stringify(this.dataSource));
        setData[index].train = 0
        setData1[index].train = 1
        Vue.ls.set(DATA_MONITOR, setData, 7 * 24 * 60 * 60 * 1000)
        this.$store.commit('SET_DATA_MONITOR', setData)
        Vue.ls.set(DATA_MONITOR_TEST, setData1, 7 * 24 * 60 * 60 * 1000)
        this.$store.commit('SET_DATA_MONITOR_TEST', setData1)
        Vue.ls.set(DATA_MONITOR_INDEX, index, 7 * 24 * 60 * 60 * 1000)
        this.$store.commit('SET_DATA_MONITOR_INDEX', index)
        this.setTime()
      },
      handleTrain(id,index){
        getAction('/sys/oss/file/train',{id:id}).then((res) => {
        console.log('res',res)
        if(res.code === '200'){
          this.progressQuantity = 100
          this.$message.success('训练成功')
          this.loadData()
        }else{
          this.progressQuantity = 0
          this.$message.info(res.message)
          this.clickDisBtn = false
        }
  
        }).finally(() => {
          Vue.ls.remove(DATA_MONITOR)
          Vue.ls.remove(DATA_MONITOR_TEST)
          Vue.ls.remove(DATA_MONITOR_INDEX)
          this.clearIntval()
          this.tableLoading = false
        })
      },
      handlePreview(record) {
        console.log('record',record)
        if (record && record.url) {
          let url = window._CONFIG['onlinePreviewDomainURL'] + '?url=' + encodeURIComponent(record.url)
          window.open(url, '_blank')
        }
      }
    }
  }
</script>

<style scoped>
  @import '~@assets/less/common.less';
  .badge{
    line-height: 1.5;
    border-radius: 0.25rem;
    font-size: 12px;
    font-weight: 400;
    padding: 5px 12px;
  }
</style>
